﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication5.Models;
using MvcPaging;
using System.Web.Security;

namespace MvcApplication5.Controllers
{ 
    public class NewsController : Controller
    {
        private MvcApplication5Context db = new MvcApplication5Context();
        private const int DefaultPageSize = 10;
        private IList<News> allNews;
        //
        // GET: /News/

        public ViewResult Index()
        {
            return View(db.News.ToList());            
        }
               
        // GET: /Admin

        public ActionResult Admin()
        {
            if (Session["UserId"] == null)
            {
                return RedirectToAction("LogOn");
            }
            CheckPublished();
            return View();
        }

        public ActionResult Paging(int? page)
        {
            allNews = db.News.ToList();
            int currentPageIndex = page.HasValue ? page.Value - 1 : 0;
            return View(this.allNews.ToPagedList(currentPageIndex, DefaultPageSize));
        }

        //
        //GET: /News/TempList

        public ActionResult TempList(int? page, string UserType)
        {
            if (Session["UserId"] == null)
            {
                return RedirectToAction("LogOn");
            }
            CheckPublished();
            Session["Type"] = "TempList";
            switch (UserType)
            {
                case "TBT":
                    ViewBag.UserType = "TBT";
                    break;
                case "BTV":
                    ViewBag.UserType = "BTV";
                    break;
                case "CTV":
                    ViewBag.UserType = "CTV";
                    break;
            }
            int currentPageIndex = page.HasValue ? page.Value - 1 : 0;
            int AccountId = int.Parse(Session["UserId"].ToString());
            IEnumerable<News> newsList = db.News.Where(c => c.level == 0 && c.AccountId == AccountId).OrderByDescending(c => c.LastModifiedDate).ToList();
            return View(newsList.ToPagedList(currentPageIndex, DefaultPageSize));            
        }

        //
        //POST: /News/TempList

        [HttpPost]
        public ActionResult TempList(string submitButton,int? page, FormCollection form)
        {
            if (Session["UserId"] == null)
            {
                return RedirectToAction("LogOn");
            }
            CheckPublished();
            int temp = 0;
            switch(submitButton){
                case "Xóa tin đã chọn": 
                    temp = -1;
                    break;
                case "Gửi lên chờ biên tập": 
                    temp = 1;
                    break;
                case "Gửi lên chờ duyệt":
                    temp = 3;
                    break;
            }
            int currentPageIndex = page.HasValue ? page.Value - 1 : 0;
            var valList = form.GetValues("chkBox");
            if (valList != null)
            {
                foreach (var item in valList)
                {
                    News news = db.News.Find(Int32.Parse(item));
                    news.level = temp;
                    if (ModelState.IsValid)
                    {
                        db.Entry(news).State = EntityState.Modified;
                        db.SaveChanges();
                    }
                }
            }
            var AccountId = int.Parse(Session["UserId"].ToString());            
            IEnumerable<News> newsList = db.News.Where(c => c.level == 0 && c.AccountId == AccountId).ToList();
            return View(newsList.ToPagedList(currentPageIndex, DefaultPageSize));
        }

        //
        //GET: /News/EditWaitList

        public ActionResult EditWaitList(int? page, string UserType)
        {
            if (Session["UserId"] == null)
            {
                return RedirectToAction("LogOn");
            }
            CheckPublished();
            switch (UserType)
            {
                case "TBT":
                    ViewBag.UserType = "TBT";
                    break;
                case "BTV":
                    ViewBag.UserType = "BTV";
                    break;
                case "CTV":
                    ViewBag.UserType = "CTV";
                    break;
            }
            int currentPageIndex = page.HasValue ? page.Value - 1 : 0;
            var AccountId = int.Parse(Session["UserId"].ToString());
            var Account = db.Account.Find(AccountId);
            IEnumerable<News> newsList = new List<News>();
            if (Account.Category != "0000")
            {                
                var categoryList = from item in db.Category                                  
                                   where item.Tag.Substring(0,4) == Account.Category
                                   where item.Tag.Length == 8
                                   select item.Tag;                                
                newsList = db.News.Where(c => c.level == 1 && categoryList.Contains(c.Category.Tag)).ToList();
            }
            else
            {
                newsList = db.News.Where(c => c.level == 1).ToList();
            }
            return View(newsList.ToPagedList(currentPageIndex, DefaultPageSize));
            
        }

        //
        //POST: /News/EditWaitList
        
        [HttpPost]
        public ActionResult EditWaitList(string submitButton, int? page, FormCollection form, string UserType)
        {
            if (Session["UserId"] == null)
            {
                return RedirectToAction("LogOn");
            }
            CheckPublished();
            int temp = 0;
            switch (submitButton)
            {
                case "Xóa tin đã chọn":
                    temp = -1;
                    break;
                case "Trả tin đã chọn":
                    temp = -2;
                    break;
            }
            int currentPageIndex = page.HasValue ? page.Value - 1 : 0;
            var valList = form.GetValues("chkBox");
            if (valList != null)
            {
                foreach (var item in valList)
                {
                    News news = db.News.Find(Int32.Parse(item));
                    news.level = temp;
                    if (ModelState.IsValid)
                    {
                        db.Entry(news).State = EntityState.Modified;
                        db.SaveChanges();
                    }
                }
            }
            var Account = db.Account.Find(int.Parse(Session["UserId"].ToString()));
            IEnumerable<News> newsList = new List<News>();
            if (Account.Category != "0000")
            {
                var categoryList = from item in db.Category
                                   where item.Tag.Substring(0, 4) == Account.Category
                                   select item.Tag;
                newsList = db.News.Where(c => c.level == 1 && categoryList.Contains(c.Category.Tag)).ToList();
            }
            else
            {
                newsList = db.News.Where(c => c.level == 1).ToList();
            }
            return View(newsList.ToPagedList(currentPageIndex, DefaultPageSize));
        }
       
        //
        //GET: /News/EditingList

        public ActionResult EditingList(int? page, string UserType)
        {
            int currentPageIndex = page.HasValue ? page.Value - 1 : 0;
            
            //gán tài khoản đang sử dụng trang vào viewbag
            ViewBag.UserType = UserType;
            
            //kiểm tra đăng nhập
            if (Session["UserId"] == null)
            {
                return RedirectToAction("LogOn");
            }
            CheckPublished();
            //Session["Type"] = "EditList";
            var Account = db.Account.Find(int.Parse(Session["UserId"].ToString()));
            
            // lấy ra danh sách bài viết tương ứng với từng tài khoản
            IEnumerable<News> newsList = new List<News>();
            if (Account.Category != "0000")
            {
                var categoryList = from item in db.Category
                                   where item.Tag.Substring(0, 4) == Account.Category
                                   select item.Tag;
                newsList = db.News.Where(c => c.level == 2 && categoryList.Contains(c.Category.Tag)).ToList();
            }
            else
            {
                newsList = db.News.Where(c => c.level == 2).ToList();
            }
            return View(newsList.ToPagedList(currentPageIndex, DefaultPageSize));            
        }

        //
        //POST: /News/EditingList

        [HttpPost]
        public ActionResult Editinglist(int? page, FormCollection form, string submitButton)
        {
            int currentPageIndex = page.HasValue ? page.Value - 1 : 0;
            if (Session["UserId"] == null)
            {
                return RedirectToAction("LogOn");
            }
            CheckPublished();
            int temp = 0;
            switch (submitButton)
            {
                case "Trả tin đã chọn":
                    temp = -2;
                    break;
                case "Gửi lên chờ duyệt":
                    temp = 3;
                    break;
                case "Xóa tin đã chọn":
                    temp = -2;
                    break;
            }
            var valList = form.GetValues("chkBox");
            if (valList != null)
            {
                foreach (var item in valList)
                {
                    News news = db.News.Find(Int32.Parse(item));
                    news.level = temp;
                    if (ModelState.IsValid)
                    {
                        db.Entry(news).State = EntityState.Modified;
                        db.SaveChanges();
                    }
                }
            }
            var AccountId = int.Parse(Session["UserId"].ToString());
            var newsList = db.News.Where(c => c.level == 2 && c.AccountId == AccountId).ToList();
            return View(newsList.ToPagedList(currentPageIndex, DefaultPageSize));
        }

        //
        //GET: /News/ApproveWaitList

        public ActionResult ApproveWaitList(int? page, string UserType)
        {
            ViewBag.UserType = "TBT";
            int currentPageIndex = page.HasValue ? page.Value - 1 : 0;
            ViewBag.UserType = UserType;
            if (Session["UserId"] == null)
            {
                return RedirectToAction("LogOn");
            }
            CheckPublished();
            var AccountId = int.Parse(Session["UserId"].ToString());
            var newsList = db.News.Where(c => c.level == 3).ToList();                        
            return View(newsList.ToPagedList(currentPageIndex, DefaultPageSize));
        }

        //
        //POST: /News/ApproveWaitList

        [HttpPost]
        public ActionResult ApproveWaitList(int? page, FormCollection form, string submitButton)
        {
            ViewBag.UserType = "TBT";
            int currentPageIndex = page.HasValue ? page.Value - 1 : 0;
            if (Session["UserId"] == null)
            {
                return RedirectToAction("LogOn");
            }
            CheckPublished();
            int temp = 0;
            switch (submitButton)
            {
                case "Xóa tin đã chọn":
                    temp = -1;
                    break;
                case "Trả tin đã chọn":
                    temp = -2;
                    break;
                case "Nhận duyệt":
                    temp = 7;
                    break;
            }
            var valList = form.GetValues("chkBox");
            if (valList != null)
            {
                foreach (var item in valList)
                {
                    News news = db.News.Find(Int32.Parse(item));
                    news.level = temp;
                    if (ModelState.IsValid)
                    {
                        db.Entry(news).State = EntityState.Modified;
                        db.SaveChanges();
                    }
                }
            }
            var AccountId = int.Parse(Session["UserId"].ToString());
            var newsList = db.News.Where(c => c.level == 3).ToList();
            return View(newsList.ToPagedList(currentPageIndex, DefaultPageSize));
        }

        //
        //GET: /News/PublishWaitList

        public ActionResult PublishWaitList(int? page, string UserType)
        {
            ViewBag.UserType = "TBT";
            int currentPageIndex = page.HasValue ? page.Value - 1 : 0;
            ViewBag.UserType = UserType;
            if (Session["UserId"] == null)
            {
                return RedirectToAction("LogOn");
            }
            CheckPublished();
            var AccountId = int.Parse(Session["UserId"].ToString());
            var newsList = db.News.Where(c => c.level == 7).ToList();
            return View(newsList.ToPagedList(currentPageIndex, DefaultPageSize));
        }

        //
        //POST: /News/PublishWaitList

        [HttpPost]
        public ActionResult PublishWaitList(int? page, FormCollection form, string submitButton)
        {
            ViewBag.UserType = "TBT";
            int currentPageIndex = page.HasValue ? page.Value - 1 : 0;
            if (Session["UserId"] == null)
            {
                return RedirectToAction("LogOn");
            }
            CheckPublished();
            int temp = 0;
            switch (submitButton)
            {
                case "Xóa tin đã chọn":
                    temp = -1;
                    break;
                case "Trả tin đã chọn":
                    temp = -2;
                    break;                
            }
            var valList = form.GetValues("chkBox");
            if (valList != null)
            {
                foreach (var item in valList)
                {
                    News news = db.News.Find(Int32.Parse(item));
                    news.level = temp;
                    if (ModelState.IsValid)
                    {
                        db.Entry(news).State = EntityState.Modified;
                        db.SaveChanges();
                    }
                }
            }
            var AccountId = int.Parse(Session["UserId"].ToString());
            var newsList = db.News.Where(c => c.level == 7).ToList();
            return View(newsList.ToPagedList(currentPageIndex, DefaultPageSize));
        }

        //
        //GET: /News/TakenDownList

        public ActionResult TakenDownList(int? page)
        {
            int currentPageIndex = page.HasValue ? page.Value - 1 : 0;
            if (Session["UserId"] == null)
            {
                return RedirectToAction("LogOn");
            }
            CheckPublished();
            var AccountId = int.Parse(Session["UserId"].ToString());
            var newsList = db.News.Where(c => c.level == 9).ToList();
            return View(newsList.ToPagedList(currentPageIndex, DefaultPageSize));
        }

        //
        //POST: /News/TakenDownList
        
        [HttpPost]
        public ActionResult TakenDownList(int? page, FormCollection form)
        {
            if (Session["UserId"] == null)
            {
                return RedirectToAction("LogOn");
            }
            CheckPublished();
            int currentPageIndex = page.HasValue ? page.Value - 1 : 0;
            var valList = form.GetValues("chkBox");
            if (valList != null)
            {
                foreach (var item in valList)
                {
                    News news = db.News.Find(Int32.Parse(item));
                    news.level = -1;
                    if (ModelState.IsValid)
                    {
                        db.Entry(news).State = EntityState.Modified;
                        db.SaveChanges();
                    }
                }
            }
            var AccountId = int.Parse(Session["UserId"].ToString());
            var newsList = db.News.Where(c => c.level == 9).ToList();
            return View(newsList.ToPagedList(currentPageIndex, DefaultPageSize));
        }

        //
        // GET: /News/Published

        public ActionResult Published(int? page, string Search)
        {
            if (Session["UserId"] == null)
            {
                return RedirectToAction("LogOn");
            }
            if (Search == "null")
            {
                Session["SearchResult"] = null;
            }
            CheckPublished();
            Session["Type"] = "Published";        
            int currentPageIndex = page.HasValue ? page.Value - 1 : 0;
            IEnumerable<News> newsList = new List<News>();
            SearchModel searchModel = new SearchModel();
            if (Session["SearchResult"] == null)
            {
                newsList = db.News.Where(c => c.level == 8 || c.level == 6).OrderByDescending(c => c.PublishedDate).ToList();
            }
            else
            {
                newsList = (List<News>)Session["SearchResult"];
                searchModel.searchObject = (News)Session["SearchObject"];
            }            
            searchModel.newsList = newsList.ToPagedList(currentPageIndex, DefaultPageSize);
            searchModel.categoryList = db.Category.ToList();
            searchModel.authorList = db.Author.ToList();
            searchModel.accountList = db.Account.Where(c => c.Category != "0000").ToList();
            return View(searchModel);            
        }

        //
        // POST: /News/Published

        [HttpPost]
        public ActionResult Published(int? page, string submitButton, News searchObject, FormCollection form, string type)
        {
            
            if (Session["UserId"] == null)
            {
                return RedirectToAction("LogOn");
            }
            CheckPublished();
            //xử lý gỡ tin            
            if (submitButton == "gỡ tin đã chọn")
            {
                int currentPageIndex = page.HasValue ? page.Value - 1 : 0;
                var valList = form.GetValues("chkBox");
                if (valList != null)
                {
                    foreach (var item in valList)
                    {
                        News news = db.News.Find(Int32.Parse(item));
                        news.level = -1;
                        if (ModelState.IsValid)
                        {
                            db.Entry(news).State = EntityState.Modified;
                            db.SaveChanges();
                        }
                    }
                }
                
                IEnumerable<News> newsList = db.News.Where(c => c.level == 8).ToList();
                var categoryList = (from item in db.Category
                                    select item).ToList<Category>();
                SearchModel searchModel = new SearchModel();
                searchModel.newsList = newsList.ToPagedList(currentPageIndex, DefaultPageSize);
                searchModel.categoryList = db.Category.ToList();
                searchModel.authorList = db.Author.ToList();
                return View(searchModel);                
            }else{
                //xử lý tìm kiếm
                int currentPageIndex = page.HasValue ? page.Value - 1 : 0;
                IEnumerable<News> newsList = Search(searchObject,8);
                ViewBag.Type = "Search";
                SearchModel searchModel = new SearchModel();
                searchModel.newsList = newsList.ToPagedList(currentPageIndex, DefaultPageSize);
                searchModel.categoryList = db.Category.ToList();
                searchModel.authorList = db.Author.ToList();
                searchModel.searchObject = searchObject;
                return View(searchModel);                   
            }            
        }

        //
        // GET: /News/Details/5

        public ActionResult Details(int id)
        {
            if (Session["UserId"] == null)
            {
                return RedirectToAction("LogOn");
            }
            CheckPublished();
            CreateModel createModel = new CreateModel();
            News news = db.News.Find(id);            
            var query = from item in db.Category
                        select item;
            createModel.News = news;
            createModel.categoryList = query.ToList();
            return View(createModel);
        }
        
        //
        // GET: /News/Create

        public ActionResult Create(string UserType)
        {
            if (Session["UserId"] == null)
            {
                return RedirectToAction("LogOn");
            }
            CheckPublished();
            ViewBag.UserType = UserType;
            CreateModel createModel = new CreateModel();            
            var Account = db.Account.Find(int.Parse(Session["UserId"].ToString()));
            if (Account.Category != "0000")
            {
                var categoryList = from item in db.Category
                                   where item.Tag.Substring(0, 4) == Account.Category
                                   where item.Tag.Length == 8
                                   select item;
                createModel.categoryList = categoryList;
            }
            else
            {
                createModel.categoryList = db.Category.Where(c => c.Tag.Length == 8).ToList();
            }
            createModel.authorList = db.Author.ToList();
            createModel.relatedList = new List<RelatedDetails>();
            return View(createModel);
        } 

        //
        // POST: /News/Create

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Create(News news, string UserType)
        {
            if (Session["UserId"] == null)
            {
                return RedirectToAction("LogOn");
            }
            CheckPublished();
            if (ModelState.IsValid)
            {
                news.LastModifiedBy = Session["Username"].ToString();
                news.level = 0;
                db.News.Add(news);
                db.SaveChanges();
                return RedirectToAction("TempList", new{ UserType = UserType });               
            }
            CreateModel createModel = new CreateModel();                        
            createModel.News = news;
            var Account = db.Account.Find(int.Parse(Session["UserId"].ToString()));
            if (Account.Category != "0000")
            {
                var categoryList = from item in db.Category
                                   where item.Tag.Substring(0, 4) == Account.Category
                                   where item.Tag.Length == 8
                                   select item;
                createModel.categoryList = categoryList;
            }
            else
            {
                createModel.categoryList = db.Category.Where(c => c.Tag.Length == 8).ToList();
            }            
            createModel.authorList = db.Author.ToList();
            return View(createModel);            
        }
        
        //
        // GET: /News/Edit/5

        public ActionResult Back()
        {
            if (Session["UserId"] == null)
            {
                return RedirectToAction("LogOn");
            }
            return RedirectToAction("Admin");
        }
        
        //
        // GET: /News/Edit

        public ActionResult Edit(int id, string UserType, string FromPage)
        {
            if (Session["UserId"] == null)
            {
                return RedirectToAction("LogOn");
            }
            CheckPublished();
            ViewBag.UserType = UserType;            
            ViewBag.FromPage = FromPage;            
            CreateModel createModel = new CreateModel();
            List<News> relatedNewsList = new List<News>();
            List<Tag> tagList = new List<Tag>();
            News news = db.News.Find(id);            
            createModel.News = news;
            var Account = db.Account.Find(int.Parse(Session["UserId"].ToString()));
            if (Account.Category != "0000")
            {
                var categoryList = from item in db.Category
                                   where item.Tag.Substring(0, 4) == Account.Category
                                   where item.Tag.Length == 8
                                   select item;
                createModel.categoryList = categoryList;
            }
            else
            {
                createModel.categoryList = db.Category.Where(c => c.Tag.Length == 8).ToList();
            }
            createModel.authorList = db.Author.ToList();
            var query = (from item in db.RelatedDetail
                        where item.NewsId == id
                        select item.RelatedNewsId).ToList<int>();

            foreach (var item in query)
            {
                relatedNewsList.Add(db.News.Find(item));
            }
            var query2 = (from item in db.TagDetail
                         where item.NewsId == id
                         select item.TagId).ToList<int>();

            foreach (var item in query2)
            {
                tagList.Add(db.Tag.Find(item));
            }
            createModel.relatedNewsList = relatedNewsList;
            createModel.tagList = tagList;
            return View(createModel);            
        }
        
        //
        // POST: /News/Edit/5

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(string submitButton, News news, string UserType, string FromPage, int? Year, int? Month, int? Day, int? Hour, int? Minute, int? Second, DateTime datepicker)
        {            
            if (Session["UserId"] == null)
            {
                return RedirectToAction("LogOn");
            }            
            CheckPublished();
            switch (submitButton)
            {
                case "Gửi lên chờ biên tập":
                    news.level = 1;
                    break;
                case "Nhận biên tập":
                    news.level = 2;
                    break;
                case "Gửi lên chờ duyệt":
                    news.level = 3;
                    break;
                case "Nhận duyệt":
                    news.level = 7;
                    break;
                case "Xuất bản":
                    
                    if (Year != null && Month != null && Day != null && Hour != null && Minute != null && Second != null)
                    {
                        DateTime publishDate = new DateTime(Year.Value, Month.Value, Day.Value, Hour.Value, Minute.Value, Second.Value);
                        news.PublishedDate = publishDate;
                        news.LastModifiedDate = DateTime.Now;
                        news.level = 6;
                        break;
                    }
                    else
                    {
                        news.PublishedDate = DateTime.Now;
                        news.LastModifiedDate = DateTime.Now;
                        news.level = 8;
                        news.PublishedBy = Session["Username"].ToString();
                        break;
                    }                    
                case "Lưu":
                    switch (FromPage){                                          
                        case "TempList":
                            news.level = 0;
                            break;
                        case "EditWaitList":
                            news.level = 1;
                            break;
                        case "EdittingList":
                            news.level = 2;
                            break;
                        case "ApproveWaitList":
                            news.level = 3;
                            break;
                        case "PublishWaitList":
                            news.level = 7;
                            break;      
                        case "Published":
                            DateTime temp = new DateTime(datepicker.Year, datepicker.Month, datepicker.Day, Hour.Value, Minute.Value, Second.Value);
                            news.PublishedDate = temp;
                            if (news.PublishedDate < DateTime.Now)
                            {
                                news.level = 8;
                                news.LastModifiedDate = DateTime.Now;
                                news.PublishedBy = Session["Username"].ToString();
                                break;
                            }
                            else
                            {
                                news.level = 6;
                                news.LastModifiedDate = DateTime.Now;
                                news.PublishedBy = Session["Username"].ToString();
                                break;
                            }
                        case "TakenDownList":
                            news.level = 9;
                            break;
                        case "DeletedList":
                            news.level = -1;
                            break;
                    }
                    break;
            }    
            if (ModelState.IsValid)
            {
                news.LastModifiedBy = Session["Username"].ToString();                                                
                db.Entry(news).State = EntityState.Modified;                                
                db.SaveChanges();
                switch (FromPage)
                {
                    case "TempList":
                        return RedirectToAction("TempList", new { UserType = UserType });
                    case "EditWaitList":
                        return RedirectToAction("EditWaitList", new { UserType = UserType });
                    case "EditingList":
                        return RedirectToAction("EditList", new { UserType = UserType });
                    case "ApproveWaitList":
                        return RedirectToAction("ApproveWaitList", new { UserType = UserType });
                    case "PublishWaitList":
                        return RedirectToAction("PublishWaitList", new { UserType = UserType });
                    case "Published":
                        return RedirectToAction("Published", new { UserType = UserType });                                                                                        
                    case "TakenDownList":
                        return RedirectToAction("TakenDownList", new { UserType = UserType });
                    
                }                
            }            
            CreateModel createModel = new CreateModel();
            List<News> relatedNewsList = new List<News>();            
            createModel.News = news;
            var Account = db.Account.Find(int.Parse(Session["UserId"].ToString()));
            if (Account.Category != "0000")
            {
                var categoryList = from item in db.Category
                                   where item.Tag.Substring(0, 4) == Account.Category
                                   where item.Tag.Length == 8
                                   select item;
                createModel.categoryList = categoryList;
            }
            else
            {
                createModel.categoryList = db.Category.Where(c => c.Tag.Length == 8).ToList();
            }
            createModel.authorList = db.Author.ToList();
            var query = (from item in db.RelatedDetail
                         where item.NewsId == news.NewsId
                         select item.RelatedNewsId).ToList<int>();

            foreach (var item in query)
            {
                relatedNewsList.Add(db.News.Find(item));
            }
            createModel.relatedNewsList = relatedNewsList;
            return View(createModel);            
        }
                
        //
        // GET: /News/Delete/5
 
        public ActionResult Delete(int id)
        {
            if (Session["UserId"] == null)
            {
                return RedirectToAction("LogOn");
            }
            CheckPublished();
            News news = db.News.Find(id);
            return View(news);
        }

        //
        // POST: /News/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            if (Session["UserId"] == null)
            {
                return RedirectToAction("LogOn");
            }            
            News news = db.News.Find(id);
            db.News.Remove(news);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        //
        //GET: /News/Add

        public ActionResult Add(int id, string FromPage, string UserType, int? page)
        {
            int currentPageIndex = page.HasValue ? page.Value - 1 : 0;
            ViewBag.id = id;
            ViewBag.UserType = UserType;
            ViewBag.FromPage = FromPage;
            var query = (from item in db.RelatedDetail
                         where item.NewsId == id
                         select item.RelatedNewsId).ToList<int>();
            var newsList = db.News.Where(c => c.level == 8 && !query.Contains(c.NewsId) && c.NewsId != id).ToList();
            return View(newsList.ToPagedList(currentPageIndex,DefaultPageSize));
        }
        
        
        //
        //POST: /News/Add
        [HttpPost]
        public ActionResult Add(FormCollection form, int id, string FromPage, string UserType)
        {
            ViewBag.FromPage = FromPage;
            ViewBag.UserType = UserType;
            ViewBag.NewsId = id;
            News news = db.News.Find(id);            
            
            var query = (from item in db.RelatedDetail
                         where item.NewsId == id
                         select item.RelatedNewsId).ToList<int>();
                                           
            var valList = form.GetValues("chkBox");
            if (valList != null)
            {
                foreach (var item in valList)
                {
                    News temp = db.News.Find(Int32.Parse(item));
                    RelatedDetails relatedDetails = new RelatedDetails();
                    relatedDetails.NewsId = id;
                    relatedDetails.RelatedNewsId = temp.NewsId;
                    if (ModelState.IsValid && !query.Contains(temp.NewsId))
                    {
                        db.RelatedDetail.Add(relatedDetails);
                        db.SaveChanges();                        
                    }
                }
                return RedirectToAction("Edit", new { id = id, FromPage = FromPage, UserType = UserType });
            }else{
                return RedirectToAction("Edit", new { id = id, FromPage = FromPage, UserType = UserType });
            }
            
            return View(db.News.ToList().Where(c => c.level == 8));
        }

        //
        //GET: /News/AddTag

        public ActionResult AddTag(int id, string FromPage, string UserType, int? page)
        {
            int currentPageIndex = page.HasValue ? page.Value - 1 : 0;
            ViewBag.id = id;
            ViewBag.UserType = UserType;
            ViewBag.FromPage = FromPage;
            var query = (from item in db.TagDetail
                         where item.NewsId == id
                         select item.TagId).ToList<int>();
            var tagList = db.Tag.Where(c => !query.Contains(c.TagId)).ToList();
            return View(tagList.ToPagedList(currentPageIndex, DefaultPageSize));
        }

        //
        //POST: /News/AddTag
        [HttpPost]
        public ActionResult AddTag(FormCollection form, int id, string FromPage, string UserType)
        {
            ViewBag.FromPage = FromPage;
            ViewBag.UserType = UserType;
            ViewBag.NewsId = id;
            News news = db.News.Find(id);

            var query = (from item in db.TagDetail
                         where item.NewsId == id
                         select item.TagId).ToList<int>();

            var valList = form.GetValues("chkBox");
            if (valList != null)
            {
                foreach (var item in valList)
                {
                    Tag temp = db.Tag.Find(Int32.Parse(item));
                    TagDetails tagDetails = new TagDetails();
                    tagDetails.NewsId = id;
                    tagDetails.TagId = temp.TagId;
                    if (ModelState.IsValid && !query.Contains(temp.TagId))
                    {
                        db.TagDetail.Add(tagDetails);
                        db.SaveChanges();
                    }
                }
                return RedirectToAction("Edit", new { id = id, FromPage = FromPage, UserType = UserType });
            }
            else
            {
                return RedirectToAction("Edit", new { id = id, FromPage = FromPage, UserType = UserType });
            }

            return View(db.News.ToList().Where(c => c.level == 8));
        }

        //
        //GET: /News/Remove

        public ActionResult Remove(int id, string FromPage, string UserType)
        {
            ViewBag.id = id;
            ViewBag.FromPage = FromPage;
            ViewBag.UserType = UserType;
            var query = (from item in db.RelatedDetail
                         where item.NewsId == id
                         select item.RelatedNewsId).ToList<int>();

            return View(db.News.ToList().Where(c => c.level == 8 && query.Contains(c.NewsId) && c.NewsId != id));
        }

        //
        //POST: /News/Remove
        [HttpPost]
        public ActionResult Remove(FormCollection form, int id, string FromPage, string UserType)
        {            
            ViewBag.FromPage = FromPage;
            ViewBag.UserType = UserType;
            News news = db.News.Find(id);

            var query = (from item in db.RelatedDetail
                         where item.NewsId == id
                         select item.RelatedNewsId).ToList<int>();

            var valList = form.GetValues("chkBox");
            if (valList != null)
            {
                foreach (var item in valList)
                {
                    News temp = db.News.Find(Int32.Parse(item));
                    RelatedDetails relatedDetails = new RelatedDetails();                    
                    relatedDetails = db.RelatedDetail.Where(c => c.NewsId == id && c.RelatedNewsId == temp.NewsId).First();
                    if (ModelState.IsValid)
                    {
                        db.RelatedDetail.Remove(relatedDetails);
                        db.SaveChanges();                        
                    }
                }
                return RedirectToAction("Edit", new { id = id, FromPage = FromPage, UserType = UserType });
            }
            else
            {
                return RedirectToAction("Edit", new { id = id, FromPage = FromPage, UserType = UserType });
            }
            
            return View(db.News.ToList().Where(c => c.level == 8));
        }

        //
        //GET: /News/RemoveTag

        public ActionResult RemoveTag(int id, string FromPage, string UserType)
        {
            ViewBag.id = id;
            ViewBag.FromPage = FromPage;
            ViewBag.UserType = UserType;
            var query = (from item in db.TagDetail
                         where item.NewsId == id
                         select item.TagId).ToList<int>();

            return View(db.Tag.Where(c => query.Contains(c.TagId)).ToList());
        }

        //
        //POST: /News/RemoveTag
        [HttpPost]
        public ActionResult RemoveTag(FormCollection form, int id, string FromPage, string UserType)
        {
            ViewBag.FromPage = FromPage;
            ViewBag.UserType = UserType;
            News news = db.News.Find(id);

            var query = (from item in db.TagDetail
                         where item.NewsId == id
                         select item.TagId).ToList<int>();

            var valList = form.GetValues("chkBox");
            if (valList != null)
            {
                foreach (var item in valList)
                {
                    Tag temp = db.Tag.Find(Int32.Parse(item));
                    TagDetails tagDetails = new TagDetails();
                    tagDetails = db.TagDetail.Where(c => c.NewsId == id && c.TagId == temp.TagId).First();
                    if (ModelState.IsValid)
                    {
                        db.TagDetail.Remove(tagDetails);
                        db.SaveChanges();
                    }
                }
                return RedirectToAction("Edit", new { id = id, FromPage = FromPage, UserType = UserType });
            }
            else
            {
                return RedirectToAction("Edit", new { id = id, FromPage = FromPage, UserType = UserType });
            }

            //return View(db.News.ToList().Where(c => c.level == 8));
        }

        //
        //GET: Comment

        public ActionResult Comment()
        {
            CommentModel commentModel = new CommentModel();
            commentModel.CategoryList = db.Category.ToList();            
            commentModel.CommentList = db.Comment.Where(c => c.status == 1).ToList();                                        
            return View(commentModel);
        }

        //
        //POST: Comment

        [HttpPost]
        public ActionResult Comment(string submitButton, FormCollection form)
        {
            if (Session["UserId"] == null)
            {
                return RedirectToAction("LogOn");
            }
            CheckPublished();
            CommentModel commentModel = new CommentModel();
            commentModel.CategoryList = db.Category.ToList();
            var valList = form.GetValues("chkBox");
            if (valList != null)                
                switch (submitButton)
                {   
                    case "Xóa":
                        foreach (var item in valList)
                        {
                            Comment comment = db.Comment.Find(Int32.Parse(item));
                            comment.status = -1;                            
                            if (ModelState.IsValid)
                            {
                                db.Entry(comment).State = EntityState.Modified;
                                db.SaveChanges();
                            }
                        }
                        break;
                    case "Duyệt comment đã chọn":
                        foreach (var item in valList)
                        {
                            Comment comment = db.Comment.Find(Int32.Parse(item));
                            comment.status = 2;
                            if (ModelState.IsValid)
                            {
                                db.Entry(comment).State = EntityState.Modified;
                                db.SaveChanges();
                            }
                        }
                        break;
                }
            commentModel.CommentList = db.Comment.Where(c => c.status == 1).ToList();
            return View(commentModel);
        }

        //
        //

        public ActionResult Comment2()
        {
            if (Session["UserId"] == null)
            {
                return RedirectToAction("LogOn");
            }
            CheckPublished();
            CommentModel commentModel = new CommentModel();
            commentModel.CategoryList = db.Category.ToList();
            commentModel.CommentList = db.Comment.Where(c => c.status == 0).ToList();
            return View(commentModel);
        }

        //
        //POST: Comment

        [HttpPost]
        public ActionResult Comment2(string submitButton, FormCollection form)
        {
            if (Session["UserId"] == null)
            {
                return RedirectToAction("LogOn");
            }
            CheckPublished();
            CommentModel commentModel = new CommentModel();
            commentModel.CategoryList = db.Category.ToList();
            var valList = form.GetValues("chkBox");
            if (valList != null)
                switch (submitButton)
                {
                    case "Xóa":
                        foreach (var item in valList)
                        {
                            Comment comment = db.Comment.Find(Int32.Parse(item));
                            comment.status = -1;
                            if (ModelState.IsValid)
                            {
                                db.Entry(comment).State = EntityState.Modified;
                                db.SaveChanges();
                            }
                        }
                        break;
                    case "Duyệt comment đã chọn":
                        foreach (var item in valList)
                        {
                            Comment comment = db.Comment.Find(Int32.Parse(item));
                            comment.status = 1;
                            if (ModelState.IsValid)
                            {
                                db.Entry(comment).State = EntityState.Modified;
                                db.SaveChanges();
                            }
                        }
                        break;
                }
            commentModel.CommentList = db.Comment.Where(c => c.status == 0).ToList();
            return View(commentModel);
        }

        public List<News> Search(News searchObject, int level)
        {
            string keyword = searchObject.Title != null ? searchObject.Title : "";
            List<News> result = new List<News>();
            List<int> catList = new List<int>();
            if (searchObject.CategoryId != null)
            {
                var Category = db.Category.Find(searchObject.CategoryId);
                if (Category.Tag.Length != 4)
                {
                    catList.Add(searchObject.CategoryId.Value);
                }
                else
                {
                    catList = (from item in db.Category
                                       where item.Tag.Substring(0,4).Contains(Category.Tag) && item.Tag.Length == 8
                                       select item.CategoryId).ToList<int>();
                }
            }
            else
            {
                catList = (from item in db.Category
                           select item.CategoryId).ToList<int>();
            }            
            List<int> atrList = new List<int>();            
            if (searchObject.AuthorId != null)
            {
                atrList.Add(searchObject.AuthorId.Value);
                var query = (from item in db.News
                            where item.Title.Contains(keyword) &&
                                  catList.Contains(item.CategoryId.Value) &&
                                  atrList.Contains(item.AuthorId.Value) &&
                                  item.level == level
                            select item).OrderByDescending(c => c.PublishedDate);
                result = query.ToList<News>();
            }
            else
            {
                atrList = (from item in db.Author
                           select item.AuthorId).ToList<int>();
                var query = (from item in db.News
                                  where item.Title.Contains(keyword) &&
                                  catList.Contains(item.CategoryId.Value) &&                              
                                  item.level == level
                                  select item).OrderByDescending(c => c.PublishedDate);
                result = query.ToList<News>();
            }                                    
            Session["SearchResult"] = result;
            Session["SearchObject"] = searchObject;            
            return result;
        }      

        //
        //GET: Login

        public ActionResult LogOn()
        {
            return View();
        }

        //
        //POST: Login
        [HttpPost]
        public ActionResult LogOn(Account model)
        {
            var accList = db.Account.ToList();
            foreach (var item in accList)
            {
                if (model.Username == item.Username && model.Password == item.Password)
                {
                    Session["UserId"] = item.AccountId;
                    Session["Username"] = item.Username;
                    Session["UserLevel"] = item.Level;
                    Session["UserClass"] = item.Class;
                    return RedirectToAction("Admin");                                    
                }
            }
            ModelState.AddModelError("", "Sai tên đăng nhập hoặc mật khẩu");                    
            return View(model);            
        }

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Logon", "News");
        }

        public ActionResult Statistics(DateTime? date)
        {
            if (Session["UserId"] == null)
            {
                return RedirectToAction("LogOn");
            }
            List<Statistics> statisticsList = new List<Statistics>();                        
            //foreach (var item in db.Category.ToList())
            //{
            //    StatisticsModel temp = new StatisticsModel();                
            //    temp.Category = item;
            //    temp.ArticleCount = db.News.Where(c => c.CategoryId == item.CategoryId && c.level == 8).Count();
            //    if (date == null)
            //    {
            //        foreach (var item2 in db.News.Where(c => c.CategoryId == item.CategoryId))
            //        {
            //            temp.ViewCount += item2.ViewCount;
            //        }
            //    }
            //    else
            //    {
            //        foreach (var item2 in db.News.Where(c => c.CategoryId == item.CategoryId && c.PublishedDate == date))
            //        {
            //            temp.ViewCount += item2.ViewCount;
            //        }
            //    }
            //    statisticsList.Add(temp);
            //}            
                
                DateTime date1 = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0);
                statisticsList = db.Statistics.Where(c => c.Date == date1).ToList();
                ViewBag.Date = DateTime.Now;
            return View(statisticsList);
        }

        //
        //POST: /News/Statistics

        [HttpPost]
        public ActionResult Statistics(FormCollection form, DateTime? datepicker)
        {
            List<Statistics> statisticsList = new List<Statistics>();
            //if (Session["UserId"] == null)
            //{
            //    return RedirectToAction("LogOn");
            //}
            //List<Statistics> statisticsList = new List<Statistics>();
            //var valList = form.GetValues("chkBox");
            //DateTime date = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0);
            //if (valList != null)
            //{
            //    foreach (var item in valList)
            //    {
            //        Statistics stat = new Statistics();
            //        int id = int.Parse(item);
            //        stat = db.Statistics.Where(c => c.Date == date && c.StatisticsId == id).First();
            //        statisticsList.Add(stat);    
            //    }
            //}
            if (datepicker != null)
            {
                DateTime tempDate = new DateTime(datepicker.Value.Year, datepicker.Value.Month, datepicker.Value.Day, 0, 0, 0);
                statisticsList = db.Statistics.Where(c => c.Date == datepicker).ToList();
                ViewBag.Date = tempDate;                
            }
            else
            {
                DateTime tempDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0);
                statisticsList = db.Statistics.Where(c => c.Date == tempDate).ToList();
                ViewBag.Date = DateTime.Now.ToShortDateString();
            }
            return View(statisticsList);
        }

        //
        //GET: /News/Hightlist

        public ActionResult Highlight()
        {
            return View();
        }

        public ActionResult AddAccount()
        {
            if (Session["UserId"] == null)
            {
                return RedirectToAction("LogOn");
            }
            AddAccountModel model = new AddAccountModel();
            model.categoryList = db.Category.Where(c => c.Tag.Length == 8).ToList();
            return View(model);
        }

        public ActionResult Author()
        {
            return View();
        }

        public void CheckPublished(){
            //var query = db.News.Where(c => c.level == 6);
            //foreach (var item in query.ToList())
            //{
            //    if (item.PublishedDate < DateTime.Now)
            //    {
            //        item.level = 8;
            //        db.Entry(item).State = EntityState.Modified;
            //        db.SaveChanges();
            //        db.Entry(item).State = EntityState.Detached;
            //    }
            //}
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}